<?php

namespace App\Http\Controllers\Api\V1\Wechat;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Support\generate_sign;
use Illuminate\Support\Facades\DB;
use App\Models\UsersWechat;
use App\Models\Order;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Validator;

class WechatController extends Controller
{
    private  $options;
    private  $app;

    public function __construct(){
        $this->options = config('wechat.mini_program.default');
        $this->app = Factory::miniProgram($this->options);
    }

    public function checkSignature(Request $request){
        // $userWechat = UsersWechat::find(306);
        // $token = JWTAuth::fromUser($userWechat);
        // $data=[
        //     'token'=>$token,
        // ];
        // return response()->json(['code' => 1, 'msg' => 'SUCCESS','data'=>$data]);
        $input = $request->all();
        $validator = Validator::make($input,
            [
                'encryptedData' => 'required',
                'iv' => 'required',
                'code' => 'required',
            ],[
                'required' => '字段 :attribute 不能为空.',
                'integer'=>'字段 :attribute 必须是数值',
            ]);
        if ($validator->fails()) {
            $messages = $validator->errors();
            return response()->json(['code' => -1,'msg' => $messages->first(),'data' => '',]);
        }
        $encryptedData = urldecode($request->input('encryptedData'));
        $iv = urldecode($request->input('iv'));
        $code = strval($request->input('code'));

        $app = $this->app;
        $session_key = $app->auth->session($code);
        if (array_key_exists('errcode', $session_key)) {
            return response()->json(['code' => -1, 'msg' => $session_key['errcode'].$session_key['errmsg']]);
        }
        //array:2 [
        //   "session_key" => "V/Kivbvf/SKUe/N0bjM73Q=="
        //   "openid" => "ourR35BHpsU3UVTdE5IIhxWappfs"
        // ]

        try {
            $decryptedData = $app->encryptor->decryptData($session_key['session_key'], $iv, $encryptedData);
             // array:9 [
            //   "openId" => "ourR35BHpsU3UVTdE5IIhxWappfs"
            //   "nickName" => "youth"
            //   "gender" => 1
            //   "language" => "zh_CN"
            //   "city" => "Hefei"
            //   "province" => "Anhui"
            //   "country" => "China"
            //   "avatarUrl" => "https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqhM5w8Fgv4FTO5UxhrtRkia7u8olPDzFWJ6AWeok0haLa3Q0icVJ62jV5bVdPA36mcstRBlqwOc8Sg/132"
            //   "watermark" => array:2 [
            //     "timestamp" => 1534566047
            //     "appid" => "wxe29c772a0d880d62"
            //   ]
            // ]
        } catch (\Exception $e) {
            return response()->json(['code' => -1, 'msg' => $e->getMessage()]);
        }
        $userWechat = UsersWechat::where('openid',$session_key['openid'])->first();
        if (empty($userWechat)) {
            $userWechat = new UsersWechat();
            $userWechat->openid = $session_key['openid'];
        }
        $userWechat->nickname = $decryptedData['nickName'];
        $userWechat->headimgurl = $decryptedData['avatarUrl'];
        $userWechat->province = $decryptedData['province'];
        $userWechat->country = $decryptedData['country'];
        $userWechat->city = $decryptedData['city'];
        $userWechat->sex = $decryptedData['gender'];
        $userWechat->language = $decryptedData['language'];
        $userWechat->save();

        $token = JWTAuth::fromUser($userWechat);

        $data=[
            'token'=>$token,
            'user'=>$userWechat,
        ];
        return response()->json(['code' => 1, 'msg' => 'SUCCESS','data'=>$data]);
    }


    public function appCode($path,$boxID,$optional = ['width'=>430], $scene ='get'){
        $app = $this->app;
        $response = $app->app_code->get($path, $optional);
        $name =  'box'.$boxID.'.png';
        $savePath = '/upload/qrcode/'.date('Ymd');
        $filename = $response->save(public_path($savePath),$name);
        return $savePath.'/'.$filename;
    }

    public function templateMessage($data = []){
        $app = $this->app;
        $wechat = UsersWechat::where('id',$data['wechat_id'])->first();
        switch ($data['type']) {
            case 1:
                $arr = config('wechat.mini_program.templateId');
                $template_id = $arr[0];
                $page = 'pages/my/index';
                $param = [
                    'keyword1'=>$wechat->number,
                    'keyword2'=>date('Y-m-d H:i:s'),
                    'keyword3'=>'恭喜您已成为ScalerBox专属会员',
                ];
                break;
            default:
                break;
        }
        $app->template_message->send([
            'touser' => $wechat->openid,//接收者（用户）的 openid
            'template_id' => $template_id,//template_id
            'page' => $page,
            'form_id' => $data['form_id'],
            'data' => $param,
        ]);
    }
}
